using System;
using System.Threading.Tasks;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;
using Microsoft.EntityFrameworkCore;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Repositories
{
    /// <summary>
    /// 用户仓储实现
    /// 提供用户信息管理和身份验证的数据访问功能实现，使用Entity Framework进行数据持久化
    /// </summary>
    public class UserRepository : IUserRepository
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private readonly LowCodeDbContext _dbContext;

        /// <summary>
        /// 初始化用户仓储实例
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        public UserRepository(LowCodeDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 根据OpenId获取用户
        /// 用于社交登录场景
        /// </summary>
        /// <param name="openId">社交平台OpenId</param>
        /// <returns>用户实体，如果不存在则返回null</returns>
        public async Task<User?> GetByOpenIdAsync(string openId)
        {
            return await _dbContext.Users.FirstOrDefaultAsync(u => u.OpenId == openId);
        }

        /// <summary>
        /// 添加新用户
        /// </summary>
        /// <param name="user">要添加的用户实体</param>
        /// <returns>添加操作的异步任务</returns>
        public async Task AddAsync(User user)
        {
            await _dbContext.Users.AddAsync(user);
            await _dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>用户实体，如果不存在则返回null</returns>
        public async Task<User?> GetByUsernameAsync(string username)
        {
            return await _dbContext.Users.FirstOrDefaultAsync(u => u.Username == username);
        }

        /// <summary>
        /// 根据邮箱获取用户
        /// </summary>
        /// <param name="email">邮箱地址</param>
        /// <returns>用户实体，如果不存在则返回null</returns>
        public async Task<User?> GetByEmailAsync(string email)
        {
            return await _dbContext.Users.FirstOrDefaultAsync(u => u.Email == email);
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="user">要更新的用户实体</param>
        /// <returns>更新操作的异步任务</returns>
        public async Task UpdateAsync(User user)
        {
            _dbContext.Users.Update(user);
            await _dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 检查用户名是否已存在
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>如果用户名已存在返回true，否则返回false</returns>
        public async Task<bool> ExistsAsync(string username)
        {
            return await _dbContext.Users.AnyAsync(u => u.Username == username);
        }

        /// <summary>
        /// 根据标识符获取用户
        /// </summary>
        /// <param name="id">用户标识符</param>
        /// <returns>用户实体，如果不存在则返回null</returns>
        public async Task<User?> GetByIdAsync(long id)
        {
            return await _dbContext.Users.FindAsync(id);
        }

        /// <summary>
        /// 用户注册
        /// 创建新用户并进行密码哈希处理
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="email">邮箱地址</param>
        /// <param name="password">明文密码</param>
        /// <param name="phone">手机号码，可选</param>
        /// <returns>注册操作的异步任务</returns>
        public async Task RegisterAsync(string username, string email, string password, string? phone = null)
        {
            var user = new User
            {
                Username = username,
                Email = email,
                PasswordHash = BCrypt.Net.BCrypt.HashPassword(password),
                Phone = phone,
                CreatedAt = DateTime.UtcNow
            };
            await AddAsync(user);
        }

        /// <summary>
        /// 用户登录
        /// 验证用户名和密码的有效性
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">明文密码</param>
        /// <returns>登录成功返回用户名，失败则抛出异常</returns>
        /// <exception cref="UnauthorizedAccessException">用户名或密码错误时抛出</exception>
        public async Task<string> LoginAsync(string username, string password)
        {
            var user = await GetByUsernameAsync(username);
            if (user == null || !BCrypt.Net.BCrypt.Verify(password, user.PasswordHash))
                throw new UnauthorizedAccessException("用户名或密码错误");
            // 这里应生成 JWT Token，简化返回用户名
            return user.Username;
        }

        /// <summary>
        /// 获取当前用户信息
        /// 简化实现，实际应结合认证上下文
        /// </summary>
        /// <returns>当前用户DTO，如果不存在则返回null</returns>
        public async Task<Application.DTOs.UserDto?> GetCurrentUserAsync()
        {
            // 这里应结合认证上下文，简化为取第一个用户
            var user = await _dbContext.Users.FirstOrDefaultAsync();
            if (user == null) return null;
            return new Application.DTOs.UserDto
            {
                Id = user.Id,
                Username = user.Username,
                Email = user.Email ?? string.Empty,
                Phone = user.Phone
            };
        }
    }
}
